﻿using CQIE.JonJack.Models;
using CQIE.JonJack.Models.Tabels;
using CQIE.JonJack.MQList.IOServices;
using CQIE.JonJack.UtilitySource;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;

namespace CQIE.JonJack.MQList
    {
    public class PublicMQObserver : IMQObserver
     {
            private readonly PublicService _publicService;
        private readonly BookService _bookService;

        public PublicMQObserver(PublicService publicService, BookService bookService)
        {
            _publicService = publicService;
            _bookService = bookService;
        }

        public override void OpenListen()
            {
                //开启用户登录监听
               
                //开启获取所有图书监听
                this.DestructBook();

                this.SetNewBook();
            this.BorrowBook();
            this.ReturnBook();

                Console.WriteLine("已开启接口监听");
            }
           
        #region 获取图书注销
       
        public void DestructBook()
        {
            //创建连接工厂对象
            IConnectionFactory factory = new ConnectionFactory
            {
                HostName = "127.0.0.1", //IP地址
                Port = 5672, //端口号
                UserName = "guest", //用户账号
                Password = "guest" //用户密码
            };

            //创建连接和通道
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();

            try
            {
                #region 项目B监听接收登录的队列消息
                // 使用已定义的队列名称
                string queueName = "booksRequest-queue";
                
                //同一时刻，服务器只发一条消息给消费者
                channel.BasicQos(0, 1, false);

                // 设置消费者监听队列
                var consumer = new EventingBasicConsumer(channel);
                //配置消费者对象 
                consumer.Received += (model, ea) =>
                {
                    bool processed = true;

                    try
                    {
                        var body = ea.Body.ToArray();
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received '{0}':'{1}'", ea.RoutingKey, message);

                        int bid=int.Parse(message);

                        _bookService.destructBook(bid);
                    }
                    catch
                    {
                        processed = false;
                    }

                    if (processed)
                    {
                        //发送确认回执
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                };

                string consumerTag = "booksRequest-consumer";
                //注册消费者
                channel.BasicConsume(queueName, false, consumerTag, false, false, null, consumer);
                #endregion


            }
            finally
            {
                //确保在退出前关闭连接和通道
                //channel.Close();
                //connection.Close();
            }

        }
        #endregion

        #region 图书新增
        public void SetNewBook()
        {
            //创建连接工厂对象
            IConnectionFactory factory = new ConnectionFactory
            {
                HostName = "127.0.0.1", //IP地址
                Port = 5672, //端口号
                UserName = "guest", //用户账号
                Password = "guest" //用户密码
            };

            //创建连接和通道
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();

            try
            {
                #region 项目B监听接收登录的队列消息
                // 使用已定义的队列名称
                string queueName = "booksResponse-queue";

                //同一时刻，服务器只发一条消息给消费者
                channel.BasicQos(0, 1, false);

                // 设置消费者监听队列
                var consumer = new EventingBasicConsumer(channel);
                //配置消费者对象 
                consumer.Received += (model, ea) =>
                {
                    bool processed = true;

                    try
                    {
                        var body = ea.Body.ToArray();
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received '{0}':'{1}'", ea.RoutingKey, message);

                        _bookService.setNewBook(message);
                    }
                    catch
                    {
                        processed = false;
                    }

                    if (processed)
                    {
                        //发送确认回执
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                };

                string consumerTag = "booksResponse-queue";
                //注册消费者
                channel.BasicConsume(queueName, false, consumerTag, false, false, null, consumer);
                #endregion


            }
            finally
            {
                //确保在退出前关闭连接和通道
                //channel.Close();
                //connection.Close();
            }
        }

        #endregion

        public void BorrowBook()
        {
            string JWTResult = "";

            //创建连接工厂对象
            IConnectionFactory factory = new ConnectionFactory
            {
                HostName = "127.0.0.1", //IP地址
                Port = 5672, //端口号
                UserName = "guest", //用户账号
                Password = "guest" //用户密码
            };

            //创建连接和通道
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();

            try
            {
                #region 项目B监听接收登录的队列消息
                // 使用已定义的队列名称
                string queueName = "login-queue";

                //同一时刻，服务器只发一条消息给消费者
                channel.BasicQos(0, 1, false);

                // 设置消费者监听队列
                var consumer = new EventingBasicConsumer(channel);
                //配置消费者对象
                consumer.Received += (model, ea) =>
                {
                    bool processed = true;

                    try
                    {
                        var body = ea.Body.ToArray();
                        var message = Encoding.UTF8.GetString(body);
                        Console.WriteLine(" [x] Received '{0}':'{1}'", ea.RoutingKey, message);
                        // 反序列化JSON字符串为匿名对象
                        var messageObject = JsonConvert.DeserializeObject<dynamic>(message);

                        // 访问schoolNumber和passWord的值
                        string bookId = messageObject!.bookId;
                        string endTime = messageObject!.endTime;
                        string schoolNumber=messageObject!.schoolNumber;
                        //调用IO层的登录操作
                         _publicService.BorrowBook(bookId, endTime, schoolNumber);

                    }
                    catch
                    {
                        processed = false;
                    }

                    if (processed)
                    {
                        //发送确认回执
                        channel.BasicAck(ea.DeliveryTag, false);
                    }
                };

                string consumerTag = "login-consumer";
                //注册消费者
                channel.BasicConsume(queueName, false, consumerTag, false, false, null, consumer);
                #endregion


            }
            finally
            {
                //确保在退出前关闭连接和通道
                //channel.Close();
                //connection.Close();
            }
        }

        public void ReturnBook()
        {
            // 建立队列工厂
            IConnectionFactory factory = new ConnectionFactory
            {
                HostName = "127.0.0.1", // IP地址
                Port = 5672, // 端口号
                UserName = "guest", // 用户账号
                Password = "guest" // 用户密码
            };

            // 项目A接收响应队列
            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();

            // 使用已定义的队列名称
            string queueName = "loginResponse-queue";

            // 同一时刻，服务器只发一条消息给消费者
            channel.BasicQos(0, 1, false);

            // 设置消费者监听队列
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body.ToArray();
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received '{0}':'{1}'", ea.RoutingKey, message);

                // 反序列化JSON字符串为匿名对象
                var messageObject = JsonConvert.DeserializeObject<dynamic>(message);

                // 访问schoolNumber和passWord的值
                string bookId = messageObject!.bookId;
                string schoolNumber = messageObject!.schoolNumber;

                using (_DbContext Db=new())
                {
                    User user = Db.User.Where(u => u.SchoolNumber ==schoolNumber)
              .Include(u => u.BorrowRecords)!
              .ThenInclude(b => b.Book).Single();

                    user.BorrowRecords.Where(b => b.BookId == int.Parse(bookId)).Single().ReturnTime = DateTime.Now;

                    Db.SaveChanges();
                }

                // 发送确认回执
                channel.BasicAck(ea.DeliveryTag, false);
            };

            string consumerTag = "loginResponse-consumer";
            channel.BasicConsume(queueName, false, consumerTag, false, false, null, consumer);

        }
    }
}
